<?php
/*
 * @Description:
 * @Author: 橘子味的心
 * @Date: 2021-01-19 06:57:52
 * @LastEditTime: 2021-03-26 17:53:59
 * @LastEditors: 橘子味的心
 * @Reference:
 */
declare (strict_types = 1);

namespace x_mier\auth\middleware;

use Closure;
use think\facade\Session;
use think\Request;

/**
 * 登录、Auth初始化
 */
class Auth
{
    /**
     * Auth初始化
     * @access public
     * @param Request $request
     * @param Closure $next
     * @param App     $app
     * @param Session $session
     * @return void
     */
    use \x_mier\Jump;
    public function handle($request, Closure $next, $data)
    {
        if (!is_array($data)) {
            $data = [$data];
        }
        $this->auth = new \x_mier\auth\Auth;
        $request->auth = $this->auth;
        switch ($data[0]) {
            case 'login':
                $username = $request->middleware('username') ?? $request->param('username', false);
                $password = $request->middleware('password') ?? $request->param('password', false);
                if (!$username || !$password) {
                    return tofalse(105);
                }
                $returndata = $this->auth->getLogin($username, $password);
                if ($returndata) {
                    Session::set('auth_user', $returndata);
                    Session::save();
                    return todata($returndata);
                } else {
                    return tofalse(-1, '账号密码错误');
                }
                break;
            case 'logout':
                Session::clear();
                $verification = 'system';
                if (!empty(config('app.app_map'))) {
                    if (!empty($verifications = array_flip(config('app.app_map'))['system'])) {
                        $verification = $verifications;
                    };
                }
                return $this->success('退出登录成功', '/' . $verification . '/' . $data[1]);
                break;
        }
        //是否需要判断是否已经登录
        if (!isset($data[0]) || !session('login.' . $data[0])) {
            if ($this->auth->getConfig()['url'] == '') {
                return tofalse(106);
            } else {
                return redirect($this->auth->getConfig()['url']);
            }
        }
    }
}
